package com.faxsun.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.broadleafcommerce.core.web.api.BroadleafWebServicesException;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import com.faxsun.api.service.utils.HttpContextHelper;
import com.faxsun.web.processor.RestfulProcessor;

public class RestFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        boolean isInWhiteList = false;

        // TODO: use configuration file
        String ip = HttpContextHelper.getClientIp();

        if (!StringUtils.isEmpty(ip) &&
            (ip.startsWith("192.") || ip.startsWith("10.") || ip.startsWith("127.") ||
                ip.equals("localhost") || ip.equals("0:0:0:0:0:0:0:1") || ip.equals("101.231.32.250"))) {
            isInWhiteList = true;
        }

        if (!isInWhiteList) {
            String key = req.getHeader("key");
            if (key == null || key.isEmpty()) {
                res.getWriter().write("{\"retCode\":-1,\"retVaule\":\"lack key parameter in header.\"}");
                return;
            }

            try {
                RestfulProcessor.authenticationCheck(key);
            } catch (BroadleafWebServicesException bwse) {
                res.getWriter().write("{\"retCode\":" + bwse.getHttpStatusCode() +
                    ",\"retVaule\":\"Authentication failed.\"}");
                return;
            }
        }
        chain.doFilter(req, res);

    }

}
